<template >
    <div class="app-container">
        <span style="font-size: 26px;margin-right: 20px;  color: black;">农业机械购置补贴申请表</span>
        <!-- 乡权限按钮 -->
        <span v-show="buttonShow">
            <el-button
                v-if="(checkRole(['townNongji']) || checkRole(['town'])) && (form.status == '待处理' || form.status == '异常')"
                :loading="buttonLoading" type="primary" @click="saveForm" style="padding: 10px 40px;">提交</el-button>
            <el-button v-show="form.status == '审核中' && (checkRole(['townNongji']) || checkRole(['town']))" disabled
                type="info" style="padding: 10px 40px;">审核中</el-button>
            <el-button v-if="(checkRole(['townNongji']) || checkRole(['town'])) && form.status == '待处理' && form.node == 3"
                v-show="form.id" @click="showRejectDialog" type="danger" plain size="medium"
                style="margin-left: 20px; padding: 10px 40px; ">驳回</el-button>
            <el-button v-if="(checkRole(['townNongji']) || checkRole(['town'])) && !form.id" v-show="!isAdmin"
                @click="submitForm" type="success" plain style="margin-left: 20px; padding: 10px 40px; ">保存</el-button>

            <el-button :loading="buttonLoading" v-show="(checkRole(['townNongji']) || checkRole(['town']))"
                :disabled="!canExportPDF" type="primary" @click="exportPDF"
                style="margin-left: 20px; padding: 10px 40px; float: right;">导出PDF</el-button>
            <!-- 区权限 -->
            <el-button v-show="checkRole(['districtNonji'])" @click="saveForm" type="success" plain
                style="margin-left: 20px; padding: 10px 40px; ">保存</el-button>
            <el-button v-show="checkRole(['districtNonji'])" @click="goRegistration(form.id)" type="primary" plain
                style="margin-left: 20px; padding: 10px 20px; ">补贴登记</el-button>
        </span>
        <el-dialog title="驳回意见" :visible.sync="rejectDialogVisible" width="600px" @close="resetReject">
            <el-form :model="rejectForm" ref="rejectFormRef">
                <el-form-item label="驳回意见" prop="remark" :rules="[{ required: true, message: '请输入驳回意见', trigger: 'blur' }]">
                    <el-input type="textarea" v-model="rejectForm.remark" placeholder="请输入驳回意见" rows="6"
                        style="margin-top: 10px;"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rejectDialogVisible = false">取消</el-button>
                <el-button type="danger" :loading="rejectLoading" @click="confirmReject">确认驳回</el-button>
            </span>
        </el-dialog>
        <el-row :gutter="24">
            <el-form
                :disabled="((checkRole(['townNongji']) || checkRole(['town'])) && form.node == 3) || (form.node == 4) || (checkRole(['districtNongji']))"
                ref="elForm" :rules="rules" :model="form" size="medium" label-width="120px" label-position="left">
                <div class="card-container">
                    <el-card class="infoDiv">
                        <span class="corner-label">基本信息</span>
                        <el-row :gutter="15" style="margin-top: 40px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="身份证号" prop="idCard">
                                    <el-input v-model="form.idCard" @input="calculateAgeFromIdCard" @blur="syncHistory"
                                        placeholder="请输入18位身份证号码" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="姓名" prop="appyBy">
                                    <el-input v-model="form.appyBy" placeholder="请输入姓名" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px; margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="性别" prop="sex">
                                    <el-select :style="{ width: '100%' }" v-model="form.sex" placeholder="请选择性别" clearable>
                                        <!-- 添加选项 -->
                                        <el-option label="男" value="男"></el-option>
                                        <el-option label="女" value="女"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="年龄" prop="age">
                                    <el-input v-model="form.age" placeholder="请输入年龄" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="联系电话" prop="phone">
                                    <el-input v-model="form.phone" placeholder="请输入联系电话" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="一卡通账号" prop="bankCard">
                                    <el-input v-model="form.bankCard" placeholder="请输入一卡通账号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px;">
                            <el-col :span="7" :offset="1"
                                style="display: flex; justify-content: flex-start; align-items: center">
                                <el-form-item label="地址" prop="straName">
                                    <el-input v-model="form.straName" placeholder="请输入区名" clearable></el-input>
                                </el-form-item>
                                <!-- <span style="margin-bottom: 22px; margin-left: 10px; ">区</span> -->
                                <span style="padding-bottom: 5px;">区</span>
                            </el-col>
                            <el-col :span="7" :offset="1"
                                style="display: flex; justify-content: flex-start; align-items: center">
                                <el-form-item label="" prop="townName" label-width="0">
                                    <el-select v-model="form.townName" :loading="loading" filterable remote reserve-keyword
                                        placeholder="请选择乡镇" :style="{ width: '80%' }" @change="getVillageList" clearable>
                                        <el-option v-for="item in townNameOptions" :key="item.value" :label="item.label"
                                            :value="item.label" />
                                    </el-select>
                                </el-form-item>
                                <span style="padding-bottom: 5px;">乡</span>
                            </el-col>
                            <el-col :span="7" :offset="1"
                                style="display: flex; justify-content: flex-start; align-items: center">
                                <el-form-item prop="villageName" label-width="0">
                                    <el-select v-model="form.villageName" :loading="loading" filterable remote
                                        reserve-keyword placeholder="请选择村名" :style="{ width: '80%' }"
                                        @change="getVillageList" clearable>
                                        <el-option v-for="item in villageOptions" :key="item.value" :label="item.label"
                                            :value="item.label" />
                                    </el-select>
                                </el-form-item>
                                <span style="padding-bottom: 5px;">村</span>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="机具名称" prop="machineName">
                                    <el-select v-model="form.machineName" :remote-method="remoteQueryMachineName"
                                        :loading="loading" filterable remote reserve-keyword placeholder="请输入机具名称"
                                        :style="{ width: '100%' }" @change="getProductNameList" clearable>
                                        <el-option v-for="item in machineNameList" :key="item.value" :label="item.label"
                                            :value="item.label" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="生产厂家" prop="productName">
                                    <el-select v-model="form.productName" :loading="loading" filterable remote
                                        reserve-keyword placeholder="请选择生产厂家" :style="{ width: '100%' }"
                                        @change="getSpeModelList" clearable>
                                        <el-option v-for="item in productNameList" :key="item.value" :label="item.label"
                                            :value="item.label" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="规格型号" prop="speModel">
                                    <el-select v-model="form.speModel" :loading="loading" filterable remote reserve-keyword
                                        placeholder="请选择规格型号" :style="{ width: '100%' }" clearable>
                                        <el-option v-for="item in speModelList" :key="item.value" :label="item.label"
                                            :value="item.label" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="补贴额度" prop="moneySub">
                                    <el-input v-model="form.moneySub" placeholder="请输入补贴额度" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px;">
                            <el-col :span="18" :offset="1">
                                <el-form-item label="牌证号（需要办理牌证的机具必须填报）" prop="licenseNum" label-width="300px">
                                    <el-input v-model="form.licenseNum" placeholder="请输入牌证号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
                <div class="card-container">
                    <el-card class="infoDiv">
                        <span class="corner-label">申请资料</span>
                        <el-row :gutter="15" style="margin-top: 20px;">
                            <el-col :span="24" :offset="1" style="margin-bottom: 20px;">
                                <el-button :type="selectMaterials ? '' : 'primary'" @click="materialsHandel(0)"
                                    style="padding: 10px 40px;"
                                    :disabled="!addState && !(form.appType == '农用机车')">农用机车</el-button>
                                <el-button :type="!selectMaterials ? '' : 'primary'" @click="materialsHandel(1)"
                                    :disabled="!addState && !(form.appType == '农用配套机具')">农用配套机具</el-button>
                            </el-col>
                            <el-col :span="16" :offset="1">
                                <el-table :data="tableData[selectMaterials]" border style="width: 100%">
                                    <el-table-column prop="name" label="申请资料名称" width="220" align="left">
                                        <template #default="scope">
                                            <span v-if="scope.row.required" style="color: red">*</span>
                                            <span v-else style="padding-left: 10px;">&nbsp;</span>
                                            {{ scope.row.name }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="address" label="申请资料附件" align="center">
                                        <!-- <template #default="scope">
                                            <el-upload class="upload-demo" action="http://111.40.188.220:9060/subsidy/file/upload"
                                                :on-preview="handlePreview" :on-remove="(file) => handleRemove(file, 'appyExcel')"
                                                :on-success="(response, file) => handleSuccess(response, file, 'appyExcel')" :limit="1"
                                                :on-exceed="handleExceed" :file-list="uploadedAppyExcel">
                                                <el-button icon="el-icon-upload" plain type="primary">点击上传</el-button>
                                            </el-upload>
                                        </template> -->
                                        <template #default="scope">
                                            <div v-if="!scope.row.file">
                                                <el-upload class="upload-demo"
                                                    action="http://111.40.188.220:9060/subsidy/file/upload"
                                                    :on-preview="handlePreview"
                                                    :on-success="(response, file) => handleSuccess(response, file, scope.row)"
                                                    :on-remove="(file) => handleRemove(file, scope.row)"
                                                    :on-exceed="handleExceed" :limit="1"
                                                    :file-list="scope.row.fileList || []">
                                                    <el-button icon="el-icon-upload" plain type="primary">点击上传</el-button>
                                                </el-upload>
                                            </div>
                                            <div v-else>
                                                <el-button type="success" :disabled="false"
                                                    @click="handlePreview(scope.row)">查看</el-button>
                                                <el-button type="danger"
                                                    @click="() => handleRemove(scope.row.file, scope.row)">撤销</el-button>
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
            </el-form>
        </el-row>
    </div>
</template>
<script>
import { listSubsidyApplication, getMachineryDetail, delSubsidyApplication, addSubsidyApplication, updateSubsidyApplication, rejectSubsidyApplication, approveSubsidyApplication, queryhistoryOne } from "@/api/machinery/compliehandle";
import { checkRole, checkPermi } from '@/utils/permission'
import { delFile } from '@/api/agriculture/file'
import { listMachingModel, listMachingByName } from "@/api/machinery/compliehandle"
import { listStrativeArea } from "@/api/subsidy/strativeArea";
import { get } from "sortablejs";
import { saveAs } from 'file-saver';
import PizZip from 'pizzip';
import ImageModule from 'docxtemplater-image-module-free';
import docxtemplater from 'docxtemplater';

export default {
    beforeRouteEnter(to, from, next) {
        next(vm => {
            // 路由进入时的处理
            if (!to.query.id) {
                // 没有 id 参数时，重置表单
                // vm.resetAllForm();
            }
        });
    },
    beforeRouteUpdate(to, from, next) {
        // 路由更新时的处理（比如从 /application?id=1 变成 /application） 
        if (!to.query.id) {
            // this.resetAllForm();
            if (checkRole(['townNongji']) || checkRole(['town'])) {
                this.form = {
                    villageName: undefined,
                    townName: undefined,
                    appyBy: undefined,
                    appType: "农机补贴",
                    sex: undefined,
                    idCardAddr: undefined,
                    oftenAddr: undefined,
                    phone: undefined,
                    machineType: undefined,
                    machineNum: undefined,
                    machineRack: undefined,
                    machineEngine: undefined,
                    remark: undefined,
                    idCard: undefined,
                    bankCard: undefined,
                    status: undefined,
                    node: undefined,
                    nodeName: undefined,
                    proccResult: undefined,
                    submitBy: undefined,
                    abnormal: undefined,
                    machineName: undefined,
                    productName: undefined,
                    moneySub: undefined,
                    licenseNum: undefined,
                    speModel: undefined,
                    regiNum: undefined,
                    power: undefined,
                    price: undefined,
                    productCompany: undefined,
                    productDate: undefined,
                    saleCompany: undefined,
                    saleDate: undefined,
                    invoice: undefined,
                    age: undefined,
                    straName: '滴道区',
                    attachments: undefined,
                    listMateria: []
                };
                this.addState = true;
                this.tableData = [[
                    {
                        key: "introductionUrl",
                        name: '1.村介绍信',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "idCardFrontUrl",
                        name: '2.身份证（正面）',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "idCardBackUrl",
                        name: '3.身份证（国徽面）',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "hukouIndexUrl",
                        name: '4.户口首页',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "hukouOwnerUrl",
                        name: '5.户口本人页',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "machineCertFrontUrl",
                        name: '6.机器合格证（正面）',
                        required: false,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "machineCertBackUrl",
                        name: '7.机器合格证（反面）',
                        required: false,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "engineCertUrl",
                        name: '8.发动机合格证',
                        required: false,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "tractorCertUrl",
                        name: '9.拖拉机（收获机）行驶证',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "driverCertUrl",
                        name: '10.拖拉机（收获机）驾驶证',
                        required: false,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "machineNameUrl",
                        name: '11.机车铭牌',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "engineNameUrl",
                        name: '12.发动机铭牌',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "manufacturingNameUrl",
                        name: '13.机器出厂编号（钢号）',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "vinRubbingUrl",
                        name: '14.发动机编号（钢号）',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "bankCardUrl",
                        name: '15.本人一卡通卡',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "peopleMachineUrl",
                        name: '16.人机合影三寸',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "invoiceUrl",
                        name: '17.发票复印件',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "registrationUrl",
                        name: '18.落牌照发的登记证书',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "paymentProofUrl",
                        name: '19.现金收据或者微信截图',
                        required: false,
                        file: null,
                        fileList: []
                    },
                ],
                [
                    {
                        key: "introductionUrl",
                        name: '1.村介绍信',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "idCardFrontUrl",
                        name: '2.身份证（正面）',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "idCardBackUrl",
                        name: '3.身份证（国徽面）',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "hukouIndexUrl",
                        name: '4.户口首页',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "hukouOwnerUrl",
                        name: '5.户口本人页',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "machineCertUrl",
                        name: '6.机器合格证',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "machineNameUrl",
                        name: '7.机器铭牌',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "manufacturingNameUrl",
                        name: '8.机器出厂编号',
                        required: false,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "bankCardUrl",
                        name: '9.本人一卡通卡',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "peopleMachineUrl",
                        name: '10.人机合影三寸',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "invoiceUrl",
                        name: '11.发票',
                        required: true,
                        file: null,
                        fileList: []
                    },
                    {
                        key: "paymentProofUrl",
                        name: '12.现金收据或者微信截图',
                        required: false,
                        file: null,
                        fileList: []
                    },
                ]
                ]
            }

        }
        next();
    },
    data() {

        return {
            // 按钮loading
            loading: false,
            buttonLoading: false,
            buttonShow: false,
            saveLoading: false,
            formDisabled: false, //控制整个表格是否输入
            isAdmin: false,
            borrow: {},
            selectMaterials: 0,
            node: 0,
            addState: true,
            form: {
                villageName: undefined,
                townName: undefined,
                appyBy: undefined,
                appType: "农用机车",
                sex: undefined,
                idCardAddr: undefined,
                oftenAddr: undefined,
                phone: undefined,
                machineType: undefined,
                machineNum: undefined,
                machineRack: undefined,
                machineEngine: undefined,
                remark: undefined,
                idCard: undefined,
                bankCard: undefined,
                status: undefined,
                node: undefined,
                nodeName: undefined,
                proccResult: undefined,
                submitBy: undefined,
                abnormal: undefined,
                machineName: undefined,
                productName: undefined,
                moneySub: undefined,
                licenseNum: undefined,
                speModel: undefined,
                regiNum: undefined,
                power: undefined,
                price: undefined,
                productCompany: undefined,
                productDate: undefined,
                saleCompany: undefined,
                saleDate: undefined,
                invoice: undefined,
                age: undefined,
                straName: '滴道区',
                attachments: undefined,
                listMateria: [],
                year: new Date().getFullYear(),
            },
            requiredFields: [
                "appType",
                "appyBy",
                "idCard",
                "sex",
                "age",
                "phone",
                "straName",
                "townName",
                "villageName",
                "machineName",
                "productName",
                "speModel",
                "moneySub",
                "licenseNum",
            ],

            // 驳回弹窗相关
            rejectDialogVisible: false,
            rejectForm: {
                remark: ''
            },
            rejectLoading: false,
            rules: {
                appyBy: [{
                    required: true,
                    message: '请输入申请人',
                    trigger: 'blur'
                }],
                sex: [{
                    required: true,
                    message: '请选择性别',
                    trigger: 'change'
                }],
                idCard: [{
                    required: true,
                    message: '请输入身份证号码',
                    trigger: 'blur'
                },
                    // {
                    //     pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                    //     message: '请输入正确的身份证号',
                    //     trigger: 'blur'
                    // }
                ],
                age: [{
                    required: true,
                    message: '请输入年龄',
                    trigger: 'blur'
                }],
                phone: [{
                    required: true,
                    message: '请输入联系方式',
                    trigger: 'blur'
                }, {
                    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                    message: '请输入正确的手机号',
                    trigger: 'blur'
                }],
                straName: [{
                    required: true,
                    message: '请输入地址',
                    trigger: 'blur'
                }],
                townName: [{
                    required: true,
                    message: '请输入地址',
                    trigger: 'blur'
                }],
                villageName: [{
                    required: true,
                    message: '请输入地址',
                    trigger: 'blur'
                }],
                machineName: [{
                    required: true,
                    message: '请输入机具名称',
                    trigger: 'blur'
                }],
                productName: [{
                    required: true,
                    message: '请输入生产厂家',
                    trigger: 'blur'
                }],
                speModel: [{
                    required: true,
                    message: '请输入规格型号',
                    trigger: 'blur'
                }],
                moneySub: [{
                    required: true,
                    message: '请输入补贴额度',
                    trigger: 'blur'
                }],
                licenseNum: [{
                    required: true,
                    message: '请输入牌证号',
                    trigger: 'blur'
                }],
                fuzeren: [{
                    required: true,
                    message: '请输入责任人',
                    trigger: 'blur'
                }],
                bankCard: [{
                    required: true,
                    message: '请输入一卡通账号',
                    trigger: 'blur'
                }],
                appType: [{
                    required: true,
                    message: '请选择补贴类型',
                    trigger: 'change'
                }],
                remark: [],
            },
            sexOptions: [
                {
                    "label": "男",
                    "value": "男"
                },
                {
                    "label": "女",
                    "value": "女"
                }
            ],
            tableData: [[
                {
                    key: "introductionUrl",
                    name: '1.村介绍信',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "idCardFrontUrl",
                    name: '2.身份证（正面）',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "idCardBackUrl",
                    name: '3.身份证（国徽面）',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "hukouIndexUrl",
                    name: '4.户口首页',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "hukouOwnerUrl",
                    name: '5.户口本人页',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "machineCertFrontUrl",
                    name: '6.机器合格证（正面）',
                    required: false,
                    file: null,
                    fileList: []
                },
                {
                    key: "machineCertBackUrl",
                    name: '7.机器合格证（反面）',
                    required: false,
                    file: null,
                    fileList: []
                },
                {
                    key: "engineCertUrl",
                    name: '8.发动机合格证',
                    required: false,
                    file: null,
                    fileList: []
                },
                {
                    key: "tractorCertUrl",
                    name: '9.拖拉机（收获机）行驶证',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "driverCertUrl",
                    name: '10.拖拉机（收获机）驾驶证',
                    required: false,
                    file: null,
                    fileList: []
                },
                {
                    key: "machineNameUrl",
                    name: '11.机车铭牌',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "engineNameUrl",
                    name: '12.发动机铭牌',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "manufacturingNameUrl",
                    name: '13.机器出厂编号（钢号）',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "vinRubbingUrl",
                    name: '14.发动机编号（钢号）',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "bankCardUrl",
                    name: '15.本人一卡通卡',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "peopleMachineUrl",
                    name: '16.人机合影三寸',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "invoiceUrl",
                    name: '17.发票复印件',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "registrationUrl",
                    name: '18.落牌照发的登记证书',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "paymentProofUrl",
                    name: '19.现金收据或者微信截图',
                    required: false,
                    file: null,
                    fileList: []
                },
            ],
            [
                {
                    key: "introductionUrl",
                    name: '1.村介绍信',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "idCardFrontUrl",
                    name: '2.身份证（正面）',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "idCardBackUrl",
                    name: '3.身份证（国徽面）',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "hukouIndexUrl",
                    name: '4.户口首页',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "hukouOwnerUrl",
                    name: '5.户口本人页',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "machineCertUrl",
                    name: '6.机器合格证',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "machineNameUrl",
                    name: '7.机器铭牌',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "manufacturingNameUrl",
                    name: '8.机器出厂编号',
                    required: false,
                    file: null,
                    fileList: []
                },
                {
                    key: "bankCardUrl",
                    name: '9.本人一卡通卡',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "peopleMachineUrl",
                    name: '10.人机合影三寸',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "invoiceUrl",
                    name: '11.发票',
                    required: true,
                    file: null,
                    fileList: []
                },
                {
                    key: "paymentProofUrl",
                    name: '12.现金收据或者微信截图',
                    required: false,
                    file: null,
                    fileList: []
                },
            ]
            ],
            machineNameList: [],
            productNameList: [],
            speModelList: [],
            villageOptions: [],
            townNameOptions: []
        }
    },
    created() {
        const id = this.$route.query.id || this.$route.params.id;
        this.node = this.$route.query.node || this.$route.params.node;
        this.status = this.$route.query.status || this.$route.params.status;

        this.role = this.$store.state.user.roles[0];
        console.log("this.role", this.role);
        if (this.role == 'admin') {
            this.isAdmin = true;
        }

        if (id) {
            console.log("有id", id)
            this.addState = false;
            this.loading = true
            this.fetchDetail(id).then(() => {
                this.buttonShow = true
                if (this.form.appType == "农用机车") {
                    this.selectMaterials = 0
                } else {
                    this.selectMaterials = 1
                }
                this.tableData[this.selectMaterials] = this.fillTableData(this.tableData[this.selectMaterials], this.form.attachments)
                console.log("tableData", this.tableData);
                this.form.status = this.$route.query.status;
            });
        } else {
            this.buttonShow = true
        }
        listStrativeArea({ departmentName: this.form.straName }).then(response => {
            this.townNameOptions = response[0]?.children?.filter(item => item.type === 'town') || [];
            // if (this.townOptions.length > 0) {
            //     this.queryParams.townName = this.townOptions[0].label; // 或 .value，看你要绑定哪个
            //     this.updateVillageOptions()
            //     this.handleQuery(); // 如果你想在默认选中后立即查询
            // }
        })
    },
    computed: {
        canExportPDF() {
            // 检查所有必填字段是否都有值
            return this.requiredFields.every(field => !!this.form[field]);
        }
    },
    methods: {
        // 检查必填附件是否已上传
        checkRequiredFiles() {
            const list = this.tableData[this.selectMaterials] || [];
            for (let item of list) {
                if (item.required && !item.file) {
                    this.$message.error(`请提交【${item.name}】文件`);
                    return false;
                }
            }
            return true;
        },
        getVillageList() {
            listStrativeArea({ townName: this.form.townName }).then(response => {
                console.log("村列表数据展示", response[0].children[0].children)
                this.villageOptions = response[0].children[0].children;
                // if (this.villageOptions.length > 0) {
                //     this.queryParams.villageName = this.villageOptions[0].label; // 或 .value，看你要绑定哪个
                //     // 触发后续查询（可选）
                //     this.handleQuery(); // 如果你想在默认选中后立即查询
                // }
            })
        },
        async getProductNameList() {
            try {
                const response = await listMachingByName({ machineName: this.form.machineName });
                if (response && response.length > 0) {
                    // 转为 el-option 所需格式：{ value, label }
                    this.productNameList = Array.from(
                        response
                            .map((item, index) => ({ value: index, label: item.comName }))
                            .reduce((map, item) => {
                                if (!map.has(item.label)) {
                                    map.set(item.label, item);
                                }
                                return map;
                            }, new Map())
                            .values()
                    );
                } else {
                    this.productNameList = [];
                }
            } catch (error) {
                this.$message.error('获取信息失败');
            }
        },
        async getSpeModelList() {
            try {
                const response = await listMachingByName({ machineName: this.form.machineName, productName: this.form.productName });
                if (response && response.length > 0) {
                    // 转为 el-option 所需格式：{ value, label }
                    this.speModelList = response.map((item, index) => ({
                        value: index,
                        label: item.speModel
                    }));
                } else {
                    this.speModelList = [];
                }
            } catch (error) {
                this.$message.error('获取信息失败');
            }
        },
        async remoteQueryMachineName(queryString) {
            // 清空时不需要请求
            if (!queryString || !queryString.trim()) {
                this.machineNameList = [];
                return;
            }

            this.loading = true;

            try {
                const response = await listMachingModel({ machineName: queryString.trim() });
                console.log("dadou", response)
                const result = response; // 假设返回的是字符串数组：["黑豆1号", "黑豆2号"]

                if (Array.isArray(result)) {
                    // 转为 el-option 所需格式：{ value, label }
                    this.machineNameList = result.map((name, index) => ({
                        value: index,
                        label: name
                    }));
                } else {
                    this.machineNameList = [];
                }
            } catch (error) {
                console.error('查询生产厂家失败：', error);
                this.machineNameList = [];
            } finally {
                this.loading = false;
            }
        },
        calculateAgeFromIdCard() {
            const idCard = this.form.idCard.trim();
            // 清空年龄（如果身份证无效或未填满18位）
            if (!idCard || idCard.length !== 18) {
                this.form.age = '';
                return;
            }
            // 验证身份证号码格式（简单校验）
            const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
            if (!idCardRegex.test(idCard)) {
                this.form.age = '';
                return;
            }
            // 提取出生年份（身份证第7-10位）
            const birthYear = parseInt(idCard.substring(6, 10));
            // 获取当前年份
            const currentYear = new Date().getFullYear();
            // 计算年龄：当前年份 - 出生年份
            // （不考虑今年生日是否已过）
            const age = currentYear - birthYear;
            // 设置年龄
            this.form.age = age.toString();
        },
        syncHistory() {
            const idCard = this.form.idCard;
            queryhistoryOne({ idCard: idCard }).then(res => {
                console.log("历史信息", res);
                if (res.idCard) {
                    console.log("有历史数据")
                    this.form.appyBy = res.appyBy;
                    this.form.sex = res.sex;
                    this.form.straName = res.straName;
                    this.form.townName = res.townName;
                    this.form.villageName = res.villageName;
                    this.form.phone = res.phone;
                    // this.form.idCardAddr = res.idCardAddr;
                    // this.form.oftenAddr = res.oftenAddr;
                    this.form.bankCard = res.bankCard;
                }
            })
        },
        goRegistration(id) {
            this.$router.push({
                path: '/machinery/compliehandle/registration',
                query: { id }
            });
        },
        checkRole,
        // 新建按钮跳转
        handleCreate() {
            // 清空表单数据
            Object.keys(this.form).forEach(key => {
                this.form[key] = undefined;
            });
            // 清空其他相关状态
            this.selectMaterials = 0;
            this.node = 0;
            // 跳转页面
            this.$router.push({ path: '/machinery/compliehandle/application' });
        },
        async fetchDetail(id) {

            try {
                const res = await getMachineryDetail(id);
                if (res.code === 200 && res.data) {
                    this.form = res.data
                    this.loading = false
                    // Object.keys(this.form).forEach(key => {
                    // if (res.data[key] !== undefined) {
                    //     this.form[key] = res.data[key];
                    // }
                    // });
                    this.calculateAgeFromIdCard();
                }
            } catch (error) {
                this.$message.error('获取详情失败');
            }
        },
        getFormattedDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        saveForm: function () {
            this.$refs['elForm'].validate(valid => {
                if (valid && this.checkRequiredFiles()) {
                    if (this.form.id != undefined) {
                        this.saveLoading = true;
                        if (checkRole(['townNongji']) || checkRole(['town'])) {
                            if (this.form.status == '待处理') {
                                this.form.status = "审核中";
                            } else if (this.form.status == '异常') {
                                this.form.status = "待处理";
                            }
                            this.form.attachments = JSON.stringify(this.getAttachments(this.selectMaterials).attachments);
                            updateSubsidyApplication(this.form).then(response => {
                                // 保存成功后调用审核接口
                                if (response.code === 200) {
                                    approveSubsidyApplication({ appNum: this.form.appNum }).then(auditRes => {
                                        if (auditRes.code === 200) {
                                            this.$modal.msgSuccess("提交成功");
                                        } else {
                                            this.$modal.msgError("提交失败");
                                        }
                                    }).catch(() => {
                                        this.$modal.msgError("保存成功但审核接口异常");
                                    });
                                } else {
                                    this.$modal.msgError("保存失败");
                                }
                                // this.$modal.msgSuccess("提交成功");
                            }).finally(() => {
                                this.saveLoading = false;
                                this.$tab.closeOpenPage('/machinery/compliehandle');
                            });
                        } else if (checkRole(['districtNonji'])) {
                            updateSubsidyApplication(this.form).then(response => {
                                // 保存成功后调用审核接口
                                if (response.code === 200) {
                                    this.$modal.msgSuccess("保存成功");
                                } else {
                                    this.$modal.msgError("保存失败");
                                }
                                // this.$modal.msgSuccess("提交成功");
                            }).finally(() => {
                                this.saveLoading = false;
                            });
                        }

                    } else {
                        this.saveLoading = true;
                        addSubsidyApplication(this.form).then(response => {
                            this.$modal.msgSuccess("保存成功");
                        }).finally(() => {
                            this.saveLoading = false;
                        });
                    }
                }
            })
        },
        fillTableData(tableData, attachmentsStr) {
            if (!attachmentsStr) return tableData
            let attachments = {}
            try {
                attachments = JSON.parse(attachmentsStr)
            } catch (e) {
                console.error("attachments JSON 解析失败", e)
                return tableData
            }

            // 遍历每一组 tableData
            return tableData.map(item => {
                const url = attachments[item.key] || ""
                return {
                    ...item,
                    file: url ? url : null,
                    fileList: url
                        ? [{ name: item.name, url }]
                        : []
                }
            })
        },
        getAttachments(selectMaterials) {
            // 取出当前选择的 tableData 子数组
            const currentList = this.tableData[selectMaterials] || []

            // 把每一项 name 和 file 提取成对象
            const attachments = {}
            currentList.forEach(item => {
                attachments[item.key] = item.file
            })
            console.log("attachments", attachments);


            return { attachments }
        },
        submitForm: function () {
            this.form.submitDate = this.getFormattedDateTime();
            console.log("提交时间", this.form.submitDate)
            this.$refs['elForm'].validate(valid => {
                // this.checkFormFields()
                // if (valid) {
                if (valid && this.checkRequiredFiles() && this.checkFormFields()) {
                    this.buttonLoading = true;
                    // this.form.node = 2;
                    // this.form.status = "待处理";
                    this.form.attachments = JSON.stringify(this.getAttachments(this.selectMaterials).attachments);
                    console.log("attachments", this.attachments);

                    addSubsidyApplication(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.$tab.closeOpenPage('/machinery/compliehandle');
                    }).finally(() => {
                        this.buttonLoading = false;
                    });
                }
            })
        },
        resetForm() {
            this.$refs['elForm'].resetFields()
        },
        materialsHandel(value) {
            this.selectMaterials = value
            if (this.selectMaterials == 0) {
                this.form.appType = '农用机车'
            } else {
                this.form.appType = '农用配套机具'
            }
        },
        // 显示驳回弹窗
        showRejectDialog() {
            this.rejectDialogVisible = true;
            this.rejectForm.remark = '';
        },

        // 重置弹窗内容
        resetReject() {
            this.rejectForm.remark = '';
            this.rejectLoading = false;
        },

        // 确认驳回
        confirmReject() {
            this.$refs.rejectFormRef.validate(valid => {
                if (!valid) return;
                this.rejectLoading = true;
                // 调用接口
                rejectSubsidyApplication({
                    appNum: this.form.appNum,
                    remark: this.rejectForm.remark
                }).then(res => {
                    if (res.code === 200) {
                        this.$message.success('驳回成功');
                        this.rejectDialogVisible = false;
                        this.$tab.closeOpenPage('/machinery/compliehandle');
                    } else {
                        this.$message.error(res.msg || '驳回失败');
                    }
                }).catch(() => {
                    this.$message.error('驳回失败');
                }).finally(() => {
                    this.rejectLoading = false;
                });
            });
        },
        async exportPDF() {
            // 推荐将PDF放到public目录下，路径如下
            // const pdfPath = '/test.pdf';
            // window.open(pdfPath, '_blank');
            // 下载
            // const pdfPath = '/test.pdf';
            // const link = document.createElement('a');
            // link.href = pdfPath;
            // link.download = '农机购置与应用补贴资金申请表（个人）.pdf'; // 下载时的文件名
            // document.body.appendChild(link);
            // link.click();
            // document.body.removeChild(link);
            const docxPath = '/application.docx';  // DOCX 模板文件路径

            const imageFields = ['idCardFrontUrl', 'peopleMachineUrl', 'machineNameUrl', 'invoiceUrl']; // 图片字段列表
            let imageData = null;
            let imageArrayBuffer = null;
            // 2. 获取图片数据并转换为 ArrayBuffer
            let imageArrayBufferList = {}; // 存储图片数据

            for (let field of imageFields) {
                const file = this.tableData[this.selectMaterials].find(item => item.key == field).file;

                if (file) {
                    // 获取图片数据并转换为 ArrayBuffer
                    imageData = await fetch(file);
                    imageArrayBuffer = await imageData.arrayBuffer();

                    // 将图片数据存储到对象中
                    imageArrayBufferList[field] = imageArrayBuffer;
                }
            }

            // 2. 获取 DOCX 模板文件并转换为 ArrayBuffer
            const response = await fetch(docxPath);
            const templateData = await response.arrayBuffer();

            // 4. 使用 PizZip 处理 DOCX 文件
            const zip = new PizZip(templateData);  // 使用 pizzip 解压 DOCX 模板
            const doc = new docxtemplater(zip, {
                paragraphLoop: true,
                linebreaks: true,
                modules: [
                    // 使用 ImageModule 插件插入图片
                    new ImageModule({
                        getImage: (value, key) => imageArrayBufferList[key],
                        getSize: (afterValue, value, key) => {
                            // 设置不同图片的大小
                            if (key === 'idCardFrontUrl') {
                                return [200, 100];  // 图片 1 设置为 400x300px
                            }
                            if (key === 'peopleMachineUrl') {
                                return [100, 150];  // 图片 2 设置为 300x200px
                            }
                            return [100, 100];  // 默认图片大小为 200x200px
                        },
                    }),
                ],
            });

            // 5. 填充模板数据，替换占位符 {image1} 和 {image2}
            doc.render({
                name: this.form.appyBy,  // 替换 {name} 占位符
                sex: this.form.sex,    // 替换 {sex} 占位符
                idCard: this.form.idCard,
                straName: this.form.straName,
                townName: this.form.townName,
                villageName: this.form.villageName,
                phone: this.form.phone,
                moneySub: this.form.moneySub,
                productName: this.form.productName,
                speModel: this.form.speModel,
                machineName: this.form.machineName,
                licenseNum: this.form.licenseNum,
                age: this.form.age,
                idCardFrontUrl: 'idCardFrontUrl',
                peopleMachineUrl: 'peopleMachineUrl',
                machineNameUrl: 'machineNameUrl',
                invoiceUrl: 'invoiceUrl'
            });

            // 6. 生成新的 DOCX 文件
            const blob = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            });

            // 7. 下载 DOCX 文件
            saveAs(blob, "2025年农业机械购置补贴申请表");  // 下载文件
        },
        // 重置所有表单数据的方法
        resetAllForm() {
            // 清空表单数据
            Object.keys(this.form).forEach(key => {
                if (key === 'appType') {
                    this.form[key] = "农用机车";  // 保持默认值
                } else {
                    this.form[key] = undefined;
                }
            });
            // 重置其他相关状态
            this.selectMaterials = 0;
            this.node = 0;
            this.loading = false;

            // 重置表单校验
            if (this.$refs.elForm) {
                this.$refs.elForm.resetFields();
            }
        },
        // 上传逻辑
        handlePreview(file) {
            // const serveIpPort = "111.40.188.220";
            // let originalUrl = '';
            // if(Object.keys(file).includes('url')){
            //     originalUrl = file.url;
            // }else{
            //     originalUrl = file.response.data.filePath;
            // }

            // const fileUrl = originalUrl.replace(/http:\/\/[\d.]+/, `http://${serveIpPort}`);
            window.open(file.file);
        },
        handleRemove(file, row) {
            // delFile(file.response.data.ossId).then(response => {
            if (row.fileList[0].response && row.fileList[0].response.data.ossId) {
                delFile(row.fileList[0].response.data.ossId).then(response => {
                    this.$message.success('删除成功');
                    // this.form[formFieldName] = undefined;
                    row.file = undefined
                    row.fileList = []
                    console.log("保存的数据", row)
                }).catch(error => {
                    this.$message.error('删除失败' + (error.message || '未知错误'));
                });
            } else {
                row.file = undefined
                row.fileList = []
                console.log("保存的数据", row)
            }

        },
        handleSuccess(response, file, row) {
            console.log('上传成功:', response, file, row);
            if (response && response.code === 200) {
                const filePath = response.data.filePath.replace('172.24.254.135', '111.40.188.220');
                if (filePath) {
                    // this.form[formFieldName] = filePath; // 将 ossId 保存到表单字段
                    row.file = filePath   // 保存文件路径
                    row.fileList = [file] // el-upload 用于回显
                    this.$message.success('上传成功，已保存文件ID');
                    console.log('上传情况', this.form)

                } else {
                    this.$message.error('上传成功，但未返回 ossId');
                }
            } else {
                this.$message.error('上传失败，服务器返回错误');
            }
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，请删除现有文件后再选择新文件！`);
        },
        // 检查表单必填字段是否完整
        checkFormFields() {
            const requiredFields = [
                "appType",
                "appyBy",
                "idCard",
                "sex",
                "age",
                "phone",
                "straName",
                "townName",
                "villageName",
                "machineName",
                "productName",
                "speModel",
                "moneySub",
                "licenseNum",
            ];

            for (const field of requiredFields) {
                if (!this.form[field]) {
                    console.log('请补充完所有信息');
                    this.$message.error('请补充完所有信息，再保存');
                    return false;
                }
            }

            // 特殊检查：电话号码格式
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(this.form.phone)) {
                console.log('Invalid phone number');
                this.$message.error('联系方式格式错误，重新填写');
                return false;
            }

            return true;
        },
    }
}
</script>
<style scoped>
.app-container {
    width: 80%;
    align-items: center;
    margin-left: 10%;
    overflow-x: hidden
        /* border: 1px solid rgb(204, 28, 28); */
}

.card-container {
    position: relative;
}

.infoDiv {
    width: 100%;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    padding-top: 20px;
}

.corner-label {
    position: absolute;
    top: 0;
    left: 0;
    background: #81B337;
    /* 背景色 */
    color: white;
    /* 文字颜色 */
    padding: 2px 8px;
    /* 内边距 */
    font-size: 20px;
    /* 字体大小 */
    border-radius: 4px;
    /* 圆角，左上角和右下角有圆角（根据需求调整） */
    transform: translate(-10%, -10%);
    /* 微调位置，使其覆盖在圆角上 */
    /* 如果需要，可以设置z-index */
    z-index: 1;
}</style>